package com.apps.ftapp.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.apps.ftapp.R;
import com.apps.ftapp.activity.LessonDetailActivity;
import com.apps.ftapp.activity.MyLessonActivity;
import com.apps.ftapp.adapter.LessonNewAdapter;
import com.apps.ftapp.adapter.ListDropDownAdapter;
import com.apps.ftapp.model.LessonBean;
import com.apps.ftapp.model.LessonModel;
import com.apps.ftapp.model.LessonTypeModel;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.SharedPreferencesUtil;
import com.apps.ftapp.util.Tools;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yyydjk.library.DropDownMenu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cz.msebera.android.httpclient.Header;
import es.dmoral.toasty.Toasty;
import info.hoang8f.android.segmented.SegmentedGroup;

/**
 * A simple {@link Fragment} subclass.
 * 课程  fragment
 */
public class LessonFragment extends Fragment {


    ListView listView;
    SmartRefreshLayout refreshLayout;

    Unbinder unbinder;
    @BindView(R.id.jiaoshizige)
    RadioButton jiaoshizige;
    @BindView(R.id.jiaoshizhaipin)
    RadioButton jiaoshizhaipin;
    @BindView(R.id.segmented2)
    SegmentedGroup segmented2;
    @BindView(R.id.dropDownMenu)
    DropDownMenu dropDownMenu;
    //    @BindView(R.id.fake_status_bar)
//    View fakeStatusBar;
    @BindView(R.id.wodekecheng)
    ImageView wodekecheng;
    @BindView(R.id.tops)
    LinearLayout tops;
    private boolean isFlag = false;

    //用于记录当前是第几页
    private int curPage = 1;
    //用于记录一页应该请求多少条数据
    private int pageSize = 10;
    //用于记录总页数，在上拉的时候判断还有没有更多数据
    private boolean isEnd = false;


    private String curType;


    private String type = "1";

    private String lx = "";
    private String xd = "";
    private String xk = "";

    private String headers[] = {"类型", "学科", "学段"};
    private List<View> popupViews = new ArrayList<>();
    private List<LessonBean> lxList = new ArrayList<>();
    private ListDropDownAdapter lxAdapter;
    private ListDropDownAdapter xdAdapter;
    private List<LessonBean> xdList = new ArrayList<>();
    private ListDropDownAdapter xkAdapter;
    private List<LessonBean> xkList = new ArrayList<>();

    private LessonNewAdapter lessonAdapter;

    private final Gson gson = new Gson();

    public LessonFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.fragment_lesson, container, false);
        unbinder = ButterKnife.bind(this, view);
        loadCate();
        return view;
    }

    /**
     * 获取分类
     */
    private void loadCate() {
        RequestParams params = new RequestParams();
        Async.post("course/category", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody) + "......" + type);
                    LessonTypeModel result = gson.fromJson(new String(responseBody), LessonTypeModel.class);
                    if (Tools.isIntNull(result.getSuccess()) == 1) {
                        xkList.clear();
                        xkList.addAll(LessonBean.traXk(result.getInfo().getZpxueke()));
                        xdList.clear();
                        xdList.addAll(LessonBean.traXd(result.getInfo().getXueduan()));
                        lxList.clear();
                        lxList.addAll(LessonBean.traCategory(result.getInfo().getLeibie()));
                        initView();
                    }

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });

    }


    /**
     * @param type
     * @param lx
     * @param xd
     * @param xk
     */
    private void loadData(final String type, final String lx, final String xd, final String xk) {

        L.i("main", "loadData:::" + type);

        RequestParams params = new RequestParams();
        params.put("categoryId", type);
        if (type.equals("1")) {
            params.put("zxueke", Tools.isNull(xk));
        } else if (type.equals("2")) {
            params.put("xueke", Tools.isNull(xk));
        }

        //leibie=&xueduan=&zxueke=&page=1&categoryId=1
        params.put("xueduan", Tools.isNull(xd));
        params.put("leibie", Tools.isNull(lx));
        params.put("page", curPage);
        Async.get("course/explore", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                if (statusCode == 200) {
                    L.i("main", ":::::" + new String(responseBody));
                    LessonModel result = gson.fromJson(new String(responseBody), LessonModel.class);

//                    dataList.addAll(result.getData());
                    if (null != result.getData()) {
                        if (curPage == 1) {
                            lessonAdapter.clear();
                            lessonAdapter.notifyDataSetChanged();
                        } else {

                        }
                        lessonAdapter.addAll(result.getData());
//                        if (curPage == 1) {
//                            Toasty.normal(getContext(), "没有数据了~");
//                        }
                    }

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });

    }


    private void initView() {

        popupViews.clear();
        //init lx menu
        final ListView lxView = new ListView(getContext());
        lxView.setDividerHeight(0);
        lxAdapter = new ListDropDownAdapter(getContext(), lxList);
        lxView.setAdapter(lxAdapter);

        //类别
        lxView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                lxAdapter.setCheckItem(position);
                dropDownMenu.setTabText(position == 0 ? headers[0] : lxList.get(position).getName());
                curPage = 1;

                lx = lxList.get(position).getId();
                loadData(type, lx, xd, xk);

                dropDownMenu.closeMenu();

            }
        });

        //init xd menu
        final ListView xdView = new ListView(getContext());
        xdView.setDividerHeight(0);
        xdAdapter = new ListDropDownAdapter(getContext(), xdList);
        xdView.setAdapter(xdAdapter);
        //学段
        xdView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                if(position<)
                xdAdapter.setCheckItem(position);
                dropDownMenu.setTabText(position == 0 ? headers[0] : xdList.get(position).getName());
                curPage = 1;

                xd = xdList.get(position).getId();

                loadData(type, lx, xd, xk);

                dropDownMenu.closeMenu();
            }
        });
        //init xd menu
        final ListView xkView = new ListView(getContext());
        xkView.setDividerHeight(0);
        xkAdapter = new ListDropDownAdapter(getContext(), xkList);
        xkView.setAdapter(xkAdapter);

        //学段
        xkView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                xkAdapter.setCheckItem(position);
                dropDownMenu.setTabText(position == 0 ? headers[0] : xkList.get(position).getName());
                curPage = 1;


                xk = xkList.get(position).getId();
                loadData(type, lx, xd, xk);

                dropDownMenu.closeMenu();

            }
        });

        popupViews.add(lxView);
        popupViews.add(xkView);
        popupViews.add(xdView);


        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_lesson_listview, null);

        listView = view.findViewById(R.id.listView);

        List<LessonModel.DataBean> list = new ArrayList<>();
        lessonAdapter = new LessonNewAdapter(getContext(), R.layout.fragment_lesson_listview_item, list);
        listView.setAdapter(lessonAdapter);

        refreshLayout = view.findViewById(R.id.refreshLayout);


        L.i("main", popupViews.size() + ":::::" + headers.length);

        //init dropdownview
        dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, view);

        segmented2.setTintColor(getResources().getColor(R.color.index_zhenti_btn_color));

        String yijiName = SharedPreferencesUtil.getData(getContext(), "yijiName", "") + "";

        if (Constant.FLAG == 1) {
            jiaoshizige.setChecked(true);
            jiaoshizhaipin.setChecked(false);
            type = "1";
            Constant.FLAG = 0;
        } else if (Constant.FLAG == 2) {
            jiaoshizhaipin.setChecked(true);
            jiaoshizige.setChecked(false);
            type = "2";
            Constant.FLAG = 0;
        } else {
            if ("教师资格证".equals(yijiName)) {
                jiaoshizige.setChecked(true);
                jiaoshizhaipin.setChecked(false);
                type = "1";


            } else if ("自学考试".equals(yijiName)) {
                jiaoshizhaipin.setChecked(true);
                jiaoshizige.setChecked(false);
                type = "2";
//            jiaoshizige.setChecked(false);
            }
        }
//        refreshLayout.autoRefresh();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                LessonModel.DataBean data = (LessonModel.DataBean) adapterView.getAdapter().getItem(i);
                HashMap<String, Object> map = new HashMap();
                map.put("id", data.getId());
                map.put("title", data.getTitle());
                map.put("type", data.getType());
                isFlag = false;
                ActivitySkipUtil.skipAnotherActivity(getActivity(), LessonDetailActivity.class, map);
            }
        });


        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000);
                //一般加载数据都是在子线程中，这里我用到了handler
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        curPage = 1;
//                        myOrderAdapter.clearLists()clearLists;
                        loadData(type, lx, xd, xk);
                    }
                }, 1000);
            }
        });


        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.finishLoadMore(2000);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        isLoadMore = false;
                        curPage = curPage + 1;
                        L.i("main", "curPage...." + curPage);
                        if (!isEnd) {
                            loadData(type, lx, xd, xk);
                        } else {
                            Toasty.normal(getContext(), "没有更多啦O(∩_∩)O").show();

                        }
                    }
                }, 1000);
            }
        });


        segmented2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                switch (i) {
                    case R.id.jiaoshizige:
                        //教师资格
                        type = "1";
                        curPage = 1;
                        isFlag = true;
                        loadData(type, null, null, null);
                        break;

                    case R.id.jiaoshizhaipin:
                        //教师招聘
                        isFlag = true;
                        type = "2";
                        curPage = 1;
                        loadData(type, null, null, null);
                        break;
                }
            }
        });
        String yijiId = SharedPreferencesUtil.getData(getContext(), "yijiId", "") + "";
        L.i("main", "yijiId--------------yijiId>>>>" + yijiId);
        if ("教师资格证".equals(yijiName)) {
            type = "1";
        } else {

            type = "2";
        }

        loadData(type, null, null, null);


        wodekecheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivitySkipUtil.skipAnotherActivity(getActivity(), MyLessonActivity.class, false);
            }
        });


    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden == false) {
            if (Constant.FLAG == 1) {
                jiaoshizige.setChecked(true);
                jiaoshizhaipin.setChecked(false);
                type = "1";
                Constant.FLAG = 0;
            } else if (Constant.FLAG == 2) {
                jiaoshizhaipin.setChecked(true);
                jiaoshizige.setChecked(false);
                type = "2";
                Constant.FLAG = 0;
            }
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onPause() {
        super.onPause();
//        if (isFlag) {
//            jiaoshizhaipin.setChecked(false);
//            jiaoshizige.setChecked(false);
//        }

    }

    @Override
    public void onResume() {

        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
